import regeneratorRuntime from './runtime.js';
wx.cloud.init({
	traceUser: true,
	env: 'ceart-bh8ws'
})
const db = wx.cloud.database()
const _ = db.command

/**
 * 获取文章列表
 * @param {} page 
 */
function getPostsList(page, filter, isShow, orderBy, label) {
    let where = {}
    if (filter !== '') {
        where.title = db.RegExp({
            regexp: filter,
            options: 'i',
        })
    }
    if (isShow !== -1) {
        where.isShow = isShow
    }

    if (orderBy == undefined || orderBy == "") {
        orderBy = "createTime"
    }

    if (label != undefined && label != "") {
        where.label = db.RegExp({
            regexp: label,
            options: 'i',
        })
    }

    return db.collection('mini_posts')
        .where(where)
				.orderBy('top', 'desc')
        .orderBy(orderBy, 'desc')
        .skip((page - 1) * 10)
        .limit(10)
        .field({
            _id: true,
            author: true,
            createTime: true,
            defaultImageUrl: true,
            title: true,
            totalComments: true,
            totalVisits: true,
            totalZans: true,
            isShow: true,
            classify: true,
            label: true,
            digest: true,
						type:true,
						top:true
        }).get()
}
/**
 * 获取文章详情
 * @param {} id 
 */
function getPostDetail(id) {
    return wx.cloud.callFunction({
        name: 'postsService',
        data: {
            action: "getPostsDetail",
            id: id
        }
    })
}
/**
 * 查询可用的formId数量
 */
function querySubscribeCount(templateId) {
    return wx.cloud.callFunction({
        name: 'messageService',
        data: {
            action: "querySubscribeCount",
            templateId: templateId
        }
    })
}

function getTemplateList() {
    return wx.cloud.callFunction({
        name: 'messageService',
        data: {
            action: "getTemplateList"
        }
    })
}
function addSubscribeCount(templateIds) {
    return wx.cloud.callFunction({
        name: 'messageService',
        data: {
            action: "addSubscribeCount",
            templateIds: templateIds
        }
    })
}

/**
 * 查询可用的formId数量
 */
function addFormIds(formIds) {
	return wx.cloud.callFunction({
		name: 'messageService',
		data: {
			action: "addFormIds",
			formIds: formIds
		}
	})
}
/**
 * 查询可用的formId数量
 */
function queryFormIds() {
	return wx.cloud.callFunction({
		name: 'messageService',
		data: {
			action: "queryFormIds"
		}
	})
}

/**
 * 新增版本日志
 * @param {} log 
 */
function addReleaseLog(log, title) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "addReleaseLog",
			log: log,
			title: title
		}
	})
}
/**
 * 获取版本发布日志
 * @param {*} page 
 */
function getReleaseLogsList(page) {
	return db.collection('mini_logs')
		.where({
			key: 'releaseLogKey'
		})
		.orderBy('timestamp', 'desc')
		.skip((page - 1) * 10)
		.limit(10)
		.get()
}
/**
 * 获取消息列表
 * @param {*} page 
 */
function getNoticeLogsList(page, openId) {
	return db.collection('mini_logs')
		.orderBy('timestamp', 'desc')
		.skip((page - 1) * 10)
		.limit(10)
		.get()
}
/**
 * 获取评论列表
 */
function getCommentsList(page, flag) {
    return db.collection('mini_comments')
        .where({
            flag: flag
        })
        .orderBy('timestamp', 'desc')
        .skip((page - 1) * 10)
        .limit(10)
        .get()
}
/**
 * 更新评论状态
 * @param {*} id 
 * @param {*} flag 
 */
function changeCommentFlagById(id, flag, postId, count) {
    return wx.cloud.callFunction({
        name: 'adminService',
        data: {
            action: "changeCommentFlagById",
            id: id,
            flag: flag,
            postId: postId,
            count: count
        }
    })
}
/**
 * 获取label集合
 */
function getLabelList() {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "getLabelList"
		}
	})
}

function getHomeLabel() {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "getHomeLabel"
		}
	})
}
/**
 * 新增基础标签
 */
function addBaseLabel(labelName) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "addBaseLabel",
			labelName: labelName
		}
	})
}
/**
 * 获取label集合
 */
function updateBatchPostsLabel(label, operate, posts) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "updateBatchPostsLabel",
			posts: posts,
			operate: operate,
			label: label
		}
	})
}
/**
 * 获取classify集合
 */
function getClassifyList() {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "getClassifyList"
		}
	})
}
/**
 * 新增基础主题
 */
function addBaseClassify(classifyName, classifyDesc) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "addBaseClassify",
			classifyName: classifyName,
			classifyDesc: classifyDesc
		}
	})
}

/**
 * 修改基础主题
 */
function updateBatchPostsClassify(classify, operate, posts) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "updateBatchPostsClassify",
			posts: posts,
			operate: operate,
			classify: classify
		}
	})
}
/**
 * 删除标签
 */
function deleteConfigById(id) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "deleteConfigById",
			id: id
		}
	})
}
/**
 * 更新文章专题
 * @param {*} id 
 * @param {*} isShow 
 */
function updatePostsClassify(id, classify) {
    return wx.cloud.callFunction({
        name: 'adminService',
        data: {
            action: "updatePostsClassify",
            id: id,
            classify: classify
        }
    })
}

/**
 * 获取文章列表
 * @param {*} page 
 */
function getHomePostsList(page, keyword,isShow,orderBy,label) {
	let timestamp = new Date().getTime();
	let dayTime = timestamp - 24 * 60 * 60 * 1000;//天
	let hebTime = timestamp - 24 * 60 * 60 * 1000 * 7;//一周
	let monthTime = timestamp - 24 * 60 * 60 * 1000 * 30;//一月
	let yearTime = timestamp - 24 * 60 * 60 * 1000 * 365;//一年
	let where = { defaultImageUrl: _.exists(true) };//查询条件
	if (keyword != undefined) {
		where.title = db.RegExp({
			regexp: keyword,
			options: 'i',
		})
	}
	
	if (isShow !== -1) {
		where.isShow = isShow
	}

	if (orderBy == undefined || orderBy == "") {
		orderBy = "createTime"
	}

	if (label) {
		//分页
		switch (label) {
			case 'all':
				orderBy = "timestamp"
				break;
			case 'day':
				where.timestamp = _.gte(dayTime)
				break;
			case 'hebdomad':
				where.timestamp = _.gte(hebTime)
				break;
			case 'month':
				where.timestamp = _.gte(monthTime)
				break;
			case 'year':
				where.timestamp = _.gte(yearTime)
				break;
			case 'liulan':
				orderBy = 'totalVisits'
				break;
			case 'hot':
				orderBy = 'totalComments'
				break;
			case 'fire':
				orderBy = 'totalZans'
				break;
			case 'most':
				orderBy = 'totalCollection'
				break;
			default:
				where.label = db.RegExp({
					regexp: label,
					options: 'i',
				})
		}
	}

	return db.collection('mini_posts')
		.where(where)
		.orderBy('top', 'desc')
		.orderBy(orderBy, 'desc')
		.skip((page - 1) * 10)
		.limit(10)
		.field({
			_id: true,
			author: true,
			author_cover: true,
			createTime: true,
			defaultImageUrl: true,
			title: true,
			totalComments: true,	
			totalZans: true,
			totalVisits: true,
			totalCollection: true,
			classify: true,
			label: true,
			digest: true,
			top:true,
			type:true
		}).get()
}
function getNewPostsList(page, filter, orderBy) {
	let where = {}
	if (filter.title != undefined) {
		where.title = db.RegExp({
			regexp: filter.title,
			options: 'i',
		})
	}
	if (filter.isShow != undefined) {
		where.isShow = filter.isShow
	}
	if (filter.classify != undefined) {
		where.classify = filter.classify
	}

	if (filter.hasClassify == 1) {
		where.classify = _.nin(["", 0, undefined])
	}

	if (filter.hasClassify == 2) {
		where.classify = _.in(["", 0, undefined])
	}

	if (orderBy == undefined || orderBy == "") {
		orderBy = "createTime"
	}

	if (filter.hasLabel == 1) {
		where.label = _.neq([])
	}

	if (filter.hasLabel == 2) {
		where.label = _.eq([])
	}

	//不包含某个标签
	if (filter.containLabel == 2) {
		where.label = _.nin([filter.label])
	}

	//包含某个标签
	if (filter.containLabel == 1) {
		where.label = db.RegExp({
			regexp: filter.label,
			options: 'i',
		})
	}

	//不包含某个主题
	if (filter.containClassify == 2) {
		where.classify = _.neq(filter.classify)
	}

	//包含某个主题
	if (filter.containClassify == 1) {
		where.classify = _.eq(filter.classify)
	}


	return db.collection('mini_posts')
		.where(where)
		.orderBy(orderBy, 'desc')
		.skip((page - 1) * 10)
		.limit(10)
		.field({
			_id: true,
			author: true,
			createTime: true,
			defaultImageUrl: true,
			title: true,
			totalComments: true,
			totalVisits: true,
			totalZans: true,
			isShow: true,
			classify: true,
			label: true,
			digest: true
		}).get()
}
/**
 * 更新文章状态
 * @param {*} id 
 * @param {*} isShow 
 */
function updatePostsShowStatus(id, isShow) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "updatePostsShowStatus",
			id: id,
			isShow: isShow
		}
	})
}
/**
 * 更新文章标签
 * @param {*} id 
 * @param {*} isShow 
 */
function upsertPosts(id, data) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "upsertPosts",
			id: id,
			post: data
		}
	})
}
/**
 * 删除文章
 * @param {*} id 
 */
function deletePostById(id) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "deletePostById",
			id: id
		}
	})
}
/**
 * 更新文章标签
 * @param {*} id 
 * @param {*} isShow 
 */
function updatePostsLabel(id, label) {
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "updatePostsLabel",
			id: id,
			label: label
		}
	})
}
/**
 * 根据id获取文章明细
 * @param {*} page 
 */
function getPostsById(id) {
	return db.collection('mini_posts')
		.doc(id)
		.get()
}
/**
 * 获取评论列表
 * @param {} page 
 * @param {*} postId 
 */
function getPostComments(page, postId) {
    return db.collection('mini_comments')
        .where({
            postId: postId,
            flag: 0
        })
        .orderBy('timestamp', 'desc')
        .skip((page - 1) * 10)
        .limit(10)
        .get()
}
/**
 * 获取收藏、点赞列表
 * @param {} page 
 */
function getPostRelated(where, page) {
	return db.collection('mini_posts_related')
		.where(where)
		.orderBy('createTime', 'desc')
		.skip((page - 1) * 10)
		.limit(10)
		.get()
}
/**
 * 获取打赏码
 */
function getQrCode() {
    return wx.cloud.getTempFileURL({
        fileList: [{
            fileID: 'cloud://ceart-bh8ws.6365-ceart-bh8ws-1300171498/static/zanCode.jpg'
        }]
    })
}

/**
 * 获取海报的文章二维码url
 * @param {*} id 
 */
function getReportQrCodeUrl(id) {
    return wx.cloud.getTempFileURL({
        fileList: [{
            fileID: id,
            maxAge: 60 * 60, // one hour
        }]
    })
}

/**
 * 新增文章二维码并返回临时url
 * @param {*} id 
 * @param {*} postId 
 * @param {*} comments 
 */
function addPostQrCode(postId, timestamp) {
    return wx.cloud.callFunction({
        name: 'postsService',
        data: {
            action: "addPostQrCode",
            timestamp: timestamp,
            postId: postId
        }
    })
}

/**
 * 验证是否是管理员
 */
function checkAuthor() {
    return wx.cloud.callFunction({
        name: 'adminService',
        data: {
            action: "checkAuthor"
        }
    })
}

/**
 * 新增用户收藏文章
 */
function addPostCollection(data) {
    return wx.cloud.callFunction({
        name: 'postsService',
        data: {
            action: "addPostCollection",
            postId: data.postId,
            postTitle: data.postTitle,
            postUrl: data.postUrl,
            postDigest: data.postDigest,
            type: data.type
        }
    })
}
/**
 * 新增用户点赞
 * @param {} data 
 */
function addPostZan(data) {
    return wx.cloud.callFunction({
        name: 'postsService',
        data: {
            action: "addPostZan",
            postId: data.postId,
            postTitle: data.postTitle,
            postUrl: data.postUrl,
            postDigest: data.postDigest,
            type: data.type
        }
    })
}
/**
 * 取消喜欢或收藏
 */
function deletePostCollectionOrZan(postId, type) {
    return wx.cloud.callFunction({
        name: 'postsService',
        data: {
            action: "deletePostCollectionOrZan",
            postId: postId,
            type: type
        }
    })
}
/**
 * 新增评论
 */
function addPostComment(commentContent,accept) {
    return wx.cloud.callFunction({
        name: 'postsService',
        data: {
            action: "addPostComment",
            commentContent: commentContent,
						accept:accept
        }
    })
}
/**
 * 新增子评论
 * @param {} id 
 * @param {*} comments 
 */
function addPostChildComment(id, postId, comments,accept) {
    return wx.cloud.callFunction({
        name: 'postsService',
        data: {
            action: "addPostChildComment",
            id: id,
            comments: comments,
            postId: postId,
            accept:accept
        }
    })
}
/**
 * 发送评论通知
 * @param {} nickName 
 * @param {*} comment 
 * @param {*} blogId 
 */
function sendTemplateMessage(nickName, comment, blogId) {
    return wx.cloud.callFunction({
        name: 'messageService',
        data: {
            action: "sendTemplateMessage",
            nickName: nickName,
            message: comment,
            blogId: blogId,
            tOpenId: ""
        }
    })
}

/**
 * 上传文件
 */
function uploadFile(cloudPath, filePath) {
	return wx.cloud.uploadFile({
		cloudPath: cloudPath,
		filePath: filePath, // 文件路径
	})
}

/**
 * 获取打赏码
 */
function getTempUrl(fileID) {
	return wx.cloud.getTempFileURL({
		fileList: [{
			fileID: fileID
		}]
	})
}
function updateUserInfo(userInfo,openid){
	return wx.cloud.callFunction({
		name: 'userService',
		data: {
			action: "updateUserInfo",
			userInfo: userInfo,
			openid: openid
		}
	})
}

function getUserInfo(openid){
	return wx.cloud.callFunction({
		name: 'userService',
		data: {
			action: "getUserInfo",
			openid: openid
		}
	})
}
function getBanner(){
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "getBanner"
		}
	})
}

function getDiaryTab(){
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "getDiaryTab"
		}
	})
}

function getDiary(page){
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "getDiary",
			page:page
		}
	})
}

function updateDiary(id,data){
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "updateDiary",
			id:id,
			post:data
		}
	})
}

function delDiary(id){
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "delDiary",
			id:id
		}
	})
}

function getGlobal(){
	return wx.cloud.callFunction({
		name: 'adminService',
		data: {
			action: "getGlobal"
		}
	})
}

module.exports = {
	getPostsList: getPostsList,
	getPostDetail: getPostDetail,
	querySubscribeCount:querySubscribeCount,
	getTemplateList:getTemplateList,
	addSubscribeCount:addSubscribeCount,
	addFormIds: addFormIds,
	queryFormIds: queryFormIds,
	addReleaseLog: addReleaseLog,
	getReleaseLogsList: getReleaseLogsList,
	getNoticeLogsList: getNoticeLogsList,
	getCommentsList: getCommentsList,
	changeCommentFlagById: changeCommentFlagById,
	getLabelList: getLabelList,
	getHomeLabel: getHomeLabel,
	addBaseLabel: addBaseLabel,
	updateBatchPostsLabel: updateBatchPostsLabel,
	getClassifyList: getClassifyList,
	addBaseClassify: addBaseClassify,
	updateBatchPostsClassify: updateBatchPostsClassify,
	deleteConfigById: deleteConfigById,
	updatePostsClassify: updatePostsClassify,
	getHomePostsList:getHomePostsList,
	getNewPostsList: getNewPostsList,
	updatePostsShowStatus: updatePostsShowStatus,
	upsertPosts: upsertPosts,
	deletePostById: deletePostById,
	updatePostsLabel: updatePostsLabel,
	getPostsById: getPostsById,
	getPostComments: getPostComments,
	getPostRelated: getPostRelated,
	getQrCode: getQrCode,
	getReportQrCodeUrl: getReportQrCodeUrl,
	addPostQrCode: addPostQrCode,
	checkAuthor: checkAuthor,
	addPostCollection: addPostCollection,
	addPostZan: addPostZan,
	deletePostCollectionOrZan: deletePostCollectionOrZan,
	addPostComment: addPostComment,
	addPostChildComment: addPostChildComment,
	sendTemplateMessage: sendTemplateMessage,
	uploadFile: uploadFile,
	getTempUrl: getTempUrl,
	updateUserInfo: updateUserInfo,
	getUserInfo: getUserInfo,
	getBanner:getBanner,
	getDiaryTab:getDiaryTab,
	getDiary:getDiary,
	updateDiary:updateDiary,
	delDiary:delDiary,
	getGlobal:getGlobal
}
